#ifndef CONNECTIONS_H_
#define CONNECTIONS_H_

#include "global.h" 

/* 
 * System wide module for keeping track of active connections.  
 * 
 * Some distinguished connections are:
 * 
 *    listener: the socket binded to the well-known port of
 *    the server.
 *
 *    clients: sockets connected to client applications. 
 *
 *    connected clients: clients' connections that are
 *    not logged into the chatroom.
 *
 *    logged clients: clients' connections that are
 *    logged into the chatroom. 
 *
 * It should be noticed that:
 *
 *    all = listener + clients
 *
 *    clients = connected + logged
 *
*/

typedef enum {CONNECTED, LOGGED, ERRONEOUS} connection_status_t;
                                     
/* Module setup function */
void connections_setup();

/* Maximum fd */ 
int connections_max_fd();

/* Functions for registering and closing connections */

/* Resgisters the new connection refered to by conn_fd.
 * This connection is initially placed in "all" and "clients"
 * sets. 
*/
int connections_new(int conn_fd);

/* Removes the connection (file descriptor) from every set.
 * This funtions invokes close on the socket
*/
int connections_close(int conn_fd);



/* Functions for the listener socket */
                                   
int connections_set_listener(int new_listener);

int connections_get_listener();                            



/* Functions for accesing different sets of connections */

connection_status_t connections_get_status(int conn_fd);

/* Returns every connection (listener + clients) */
void connections_get_all(fd_set *fds);

/* Returns all connections with clients */
void connections_get_clients(fd_set *fds);

/* Returns clients' connections that are logged */
void connections_get_logged(fd_set *fds);
                                            
/* Returns clients' connections that are not logged */
void connections_get_connected(fd_set *fds);

/* Moves a connection form the connected list to 
 * the logged list. Returns 0 if success, 1 if the
 * was not in the connected list.
*/
int connections_log(int conn_fd);

/* Moves a connection form the logged list to 
 * the connected list. Returns 0 if success, 1 if the
 * was not in the logged list.
*/
int connections_logout(int conn_fd);

/* Returns the fd_set resulting form subtracting fd 
 * to source. Simbolically: result = source - fd
*/
void connections_all_but(int fd, fd_set* source, fd_set *result);
 
        
#endif